package com.haohuo.framework.http;

import java.io.*;
import java.net.Socket;
import java.net.URL;

/**
 * Copyright https://wtfu.site Inc. All Rights Reserved.
 *
 * @author 12302
 * @date 2021/12/17
 * @since 1.0
 */
public class SocketServer implements Runnable {

    Socket s;

    public SocketServer(Socket s) {
        this.s = s;
    }

    /**
     *
     */
    @Override
    public void run() {
        //输入输出流
        OutputStream os = null;
        InputStream in = null;
        try {    //打开socket输入流，并转为BufferedReader流
            in = s.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in));

            URL resource = SocketServer.class.getClassLoader().getResource("com/haohuo/framework/payload/ExecutableFile.class");

            //打开socket对象的输出流，写入响应头
            os = s.getOutputStream();
            os.write("HTTP/1.1 200 OK\r\n".getBytes());
            os.write(new String("Content-Disposition: attachment; " + "filename=" + "ExecutableFile.class\r\n").getBytes());
            os.write("\r\n".getBytes());

            //空一行，写入响应内容。
            File f = new File(resource.getFile());
            if (f.exists()) {
                FileInputStream fin = new FileInputStream(f);
                byte[] b = new byte[1024];
                int len;
                while ((len = fin.read(b)) != -1) {
                    os.write(b, 0, len);
                }
            }
            os.flush();
            //如果os流没有关闭的话，浏览器会以为内容还没传输完成，将一直显示不了内容
            os.close();

        } catch (Exception e) {
            System.out.println(e.getMessage());
            if(os != null){
                try {
                    os.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }

    }
}
